package com.example.lexiangbackend.controller;

import com.example.lexiangbackend.entity.Music;
import com.example.lexiangbackend.entity.MusicCategory;
import com.example.lexiangbackend.service.CategoryService;
import com.example.lexiangbackend.service.MusicService;
import com.example.lexiangbackend.dto.MusicUploadRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/music")
@CrossOrigin(origins = "http://localhost:8080")
public class MusicController {

    @Autowired
    private MusicService musicService;
    
    @Autowired
    private CategoryService categoryService;

    /**
     * 获取音乐列表（公开接口，无需认证）
     */
    @GetMapping
    public ResponseEntity<?> getAllMusic(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "20") int size) {
        try {
            Page<Music> musicPage = musicService.getAllMusic(page, size);
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", "获取音乐列表成功");
            response.put("music", musicPage.getContent());
            response.put("totalElements", musicPage.getTotalElements());
            response.put("totalPages", musicPage.getTotalPages());
            response.put("currentPage", page);
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "获取音乐列表失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    /**
     * 根据ID获取音乐详情（公开接口，无需认证）
     */
    @GetMapping("/{musicId}")
    public ResponseEntity<?> getMusicById(@PathVariable Long musicId) {
        try {
            Music music = musicService.getMusicById(musicId);
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", "获取音乐详情成功");
            response.put("music", music);
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "获取音乐详情失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    /**
     * 获取热门音乐（公开接口，无需认证）
     */
    @GetMapping("/popular")
    public ResponseEntity<?> getPopularMusic(@RequestParam(defaultValue = "20") int limit) {
        try {
            // 暂时返回所有音乐，按播放次数排序
            Page<Music> musicPage = musicService.getAllMusic(0, limit);
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", "获取热门音乐成功");
            response.put("music", musicPage.getContent());
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "获取热门音乐失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    /**
     * 获取推荐音乐（公开接口，无需认证）
     */
    @GetMapping("/recommended")
    public ResponseEntity<?> getRecommendedMusic(
            @RequestParam(defaultValue = "20") int limit) {
        try {
            // 获取推荐音乐 - 混合热门和最新音乐
            List<Music> recommendedMusic = musicService.getRecommendedMusic(limit);
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", "获取推荐音乐成功");
            response.put("music", recommendedMusic);
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "获取推荐音乐失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    /**
     * 搜索音乐（公开接口，无需认证）
     */
    @GetMapping("/search")
    public ResponseEntity<?> searchMusic(
            @RequestParam String keyword,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "20") int size) {
        try {
            // 暂时返回所有音乐，后续可以添加搜索逻辑
            Page<Music> musicPage = musicService.getAllMusic(page, size);
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", "搜索音乐成功");
            response.put("music", musicPage.getContent());
            response.put("keyword", keyword);
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "搜索音乐失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    /**
     * 根据分类获取音乐（公开接口，无需认证）
     */
    @GetMapping("/category/{categoryId}")
    public ResponseEntity<?> getMusicByCategory(
            @PathVariable Long categoryId,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "20") int size) {
        try {
            Page<Music> musicPage = musicService.getMusicByCategory(categoryId, page, size);
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", "获取分类音乐成功");
            response.put("music", musicPage.getContent());
            response.put("categoryId", categoryId);
            response.put("totalElements", musicPage.getTotalElements());
            response.put("totalPages", musicPage.getTotalPages());
            response.put("currentPage", page);
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "获取分类音乐失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    /**
     * 修复音乐文件路径 - 使数据库记录与实际文件匹配
     */
    @PostMapping("/fix-file-paths")
    public ResponseEntity<Map<String, Object>> fixMusicFilePaths() {
        Map<String, Object> response = new HashMap<>();
        try {
            System.out.println("开始修复音乐文件路径...");
            
            // 获取实际存在的文件
            String uploadPath = "C:/Users/Re0XIAOPA/Documents/sourcetree/lexiangworkshop/lexiangbackend/src/main/uploads/songs";
            File songsDir = new File(uploadPath);
            
            if (!songsDir.exists() || !songsDir.isDirectory()) {
                System.err.println("songs目录不存在: " + uploadPath);
                response.put("success", false);
                response.put("message", "songs目录不存在");
                return ResponseEntity.badRequest().body(response);
            }
            
            File[] audioFiles = songsDir.listFiles((dir, name) -> 
                name.toLowerCase().endsWith(".mp3") || 
                name.toLowerCase().endsWith(".wav") || 
                name.toLowerCase().endsWith(".flac"));
            
            System.out.println("找到音频文件数量: " + (audioFiles != null ? audioFiles.length : 0));
            
            if (audioFiles != null && audioFiles.length > 0) {
                // 获取所有音乐记录 - 使用大页面获取所有记录
                Page<Music> musicPage = musicService.getAllMusic(0, 1000);
                List<Music> allMusic = musicPage.getContent();
                System.out.println("数据库中音乐记录数量: " + allMusic.size());
                
                // 更新音乐记录的文件路径
                for (int i = 0; i < audioFiles.length && i < allMusic.size(); i++) {
                    Music music = allMusic.get(i);
                    String newFilePath = audioFiles[i].getName();
                    String oldFilePath = music.getFilePath();
                    
                    System.out.println("更新音乐ID " + music.getMusicId() + 
                                     " 的文件路径: " + oldFilePath + " -> " + newFilePath);
                    
                    // 创建更新请求
                    MusicUploadRequest updateRequest = new MusicUploadRequest();
                    updateRequest.setTitle(music.getName());
                    updateRequest.setArtist(music.getSinger());
                    updateRequest.setDuration(music.getDuration());
                    updateRequest.setMusicUrl(newFilePath);
                    updateRequest.setCoverUrl(music.getCoverPath());
                    updateRequest.setCategoryId(music.getCategory() != null ? music.getCategory().getCategoryId() : 1L);
                    updateRequest.setPlayCount(music.getPlayCount());
                    
                    musicService.updateMusic(music.getMusicId(), updateRequest);
                }
                
                // 如果有多余的文件，创建新的音乐记录
                for (int i = allMusic.size(); i < audioFiles.length; i++) {
                    File audioFile = audioFiles[i];
                    String fileName = audioFile.getName();
                    
                    System.out.println("为文件创建新的音乐记录: " + fileName);
                    
                    // 创建新音乐上传请求
                    MusicUploadRequest newRequest = new MusicUploadRequest();
                    newRequest.setTitle("测试音乐 " + (i + 1));
                    newRequest.setArtist("测试艺术家");
                    newRequest.setDuration(180); // 默认3分钟
                    newRequest.setMusicUrl(fileName);
                    newRequest.setCoverUrl("default_cover.jpg");
                    
                    // 设置默认分类
                    List<MusicCategory> categories = categoryService.getAllCategories();
                    if (!categories.isEmpty()) {
                        newRequest.setCategoryId(categories.get(0).getCategoryId());
                    } else {
                        newRequest.setCategoryId(1L); // 默认分类ID
                    }
                    
                    musicService.uploadMusic(newRequest);
                }
                
                response.put("success", true);
                response.put("message", "音乐文件路径修复完成");
                response.put("filesFound", audioFiles.length);
                response.put("musicRecords", allMusic.size());
                
            } else {
                response.put("success", false);
                response.put("message", "未找到音频文件");
            }
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            System.err.println("修复音乐文件路径失败: " + e.getMessage());
            e.printStackTrace();
            response.put("success", false);
            response.put("message", "修复失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
        }
    }
} 